package com.yztc.yidoutang.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.yztc.yidoutang.bean.GoodsListBean;
import com.yztc.yidoutang.http.zhuye.ZhuYeDao;
import com.yztc.yidoutang.utils.SpacesItemDecoration;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;

/**
 * 主页中ViewPager的适配器
 */
public class ZhuYeVPAdapter extends PagerAdapter {
    private Context context;
    private List<RecyclerView> pages;
    private List<String> titles;

    public ZhuYeVPAdapter(Context context, List<String> titles) {
        this.context = context;
        this.titles = titles;
        this.pages = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return titles.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(final ViewGroup container, int position) {
        String order = "";
        String space = "";
        final RecyclerView page = new RecyclerView(context);
        // 设置RecyclerView有2列，竖直排列
        page.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        // 为RecyclerView中的Item设置艰巨
        SpacesItemDecoration decoration = new SpacesItemDecoration(10);
        page.addItemDecoration(decoration);
        // 从网络中获取数据，更新RecyclerView中的数据
        if (position == 0) {
            order = "推荐";
            space = "";
        } else {
            order = "";
            space = titles.get(position);
        }
        ZhuYeDao.getGoodsList(new Subscriber<GoodsListBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(GoodsListBean goodsListBean) {
                NormalRecycleAdapter adapter = new NormalRecycleAdapter(context, goodsListBean.getData().getPics());
                page.setAdapter(adapter);
                container.addView(page);
                pages.add(page);
            }
        }, order, space);
        return page;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(pages.get(position));
    }

    /**
     * 设置RecyclerView的展示模式
     */
    public void setRecycleMode(boolean isLinear) {
        for (RecyclerView view : pages) {
            if (isLinear) { // 一列
                view.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
            } else { // 两列
                view.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
            }
        }
    }
}